package com.eastelsoft.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eastelsoft.service.LoginService;
import com.gitee.myclouds.toolbox.session.data.CurUser;
import com.gitee.myclouds.toolbox.util.MyCons;
import com.gitee.myclouds.toolbox.util.MyUtil;
import com.gitee.myclouds.toolbox.wrap.Dto;
import com.gitee.myclouds.toolbox.wrap.Dtos;

/**
 * 登录功能
 * @author wangzl
 *
 */
@Controller
@RequestMapping("/sso")
public class LoginController {
	
	@Autowired
	private LoginService loginService;

	/**
	 * 登录跳转页面
	 * @return
	 */
	@RequestMapping("/login")
	public String login() {
		return "/sso/login";
	}
	
	@RequestMapping(value="/validate", method={RequestMethod.POST}, produces="application/json")
	@ResponseBody
	public Dto validate(HttpServletRequest request, HttpSession session) {
		Dto inDto = Dtos.newDto(request);
		Dto outDto = loginService.validate(inDto);
		if (StringUtils.equals(MyCons.YesOrNo.YES.getValue().toString(), outDto.getString("code"))) {
			CurUser curUser = new CurUser();
			MyUtil.copyProperties(outDto.get("curUser"), curUser);
			curUser.setSessionId(session.getId());
			session.setAttribute(MyCons.CUR_USER, curUser);
		}
		return outDto;
	}
	
	/**
	 * 注销
	 * @param httpSession
	 * @return
	 */
	@RequestMapping("/logout")
    public Dto logout(HttpSession session) {
		session.invalidate();
        return Dtos.newDto().put2("code", "1").put2("msg", "用户安全退出成功");
    }
	
}
